package cn.hennancf.picture.tools;


import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import cn.hennancf.picture.entities.Folder;
import cn.hennancf.picture.entities.Picture;
import cn.hennancf.picture.enums.Message;

/** 
* @author  作者: 陈飞
* @date 创建时间：2017年3月11日 下午4:21:29 
* @version 1.0 
* @parameter  
* @since  
* @return  
*/
public class ImageIoUtils {
    
    final String PICTURE_SUFFIX_NO_SPOT = "png";
    final String PICTURE_SUFFIX_SPOT = ".PNG";
    final String GROUP_PICTURE_FOLDER = "F:/picture/";
    
//    获得所有图片的URL
    public List<Picture> GetFolderPictureFiles(Folder folder){
        
//        文件夹是否存在或为空 
        if (new FolderUtils().IsEmpty(folder)) {
            new ErrorUtils(Message.ERROR_PATH_OR_EMPTY).getMessage();
        }
        
//        取出文件夹里的所有图片的URL
        List<File> folderPictureFiles = new FileUtils().getPictureFiles(folder.getUrl());
        
//        取出文件夹里的所有Picture 对象
        List<Picture> folderPictures = this.getPictures(folderPictureFiles);
        return folderPictures;
    }
    
    
    
//        取出文件夹里的所有Picture 对象
    private List<Picture> getPictures(List<File> folderPictureFiles){
        List<Picture> pictures = new ArrayList<Picture>();
        for (File file : folderPictureFiles) {
            pictures.add(this.getPicture(file));
        }
        return pictures;
    }
    
    
    
//    获取一个Picture对象
    private Picture getPicture(File file){
        file.getName();
        return new Picture(file.getName(), file, file.lastModified());
    }
    
    //    拼接图片
    public File Group(List<Picture> folderPictures,String filePath) throws IOException{
        int imageWight = 1800;
        int imageHieght = 1800;
//        画图层
        BufferedImage bufferedImage=new BufferedImage(imageWight, imageHieght, BufferedImage.TYPE_3BYTE_BGR);
        
//        设置插入图片的初始位置
        int width = 0;
        int height = 0;
        int countw = 0;
        for (int i = 0; i < folderPictures.size(); i++ ) {

            Graphics graphics=bufferedImage.getGraphics();
            BufferedImage image = ImageIO.read(folderPictures.get(i).getUrl());
            
            JPanel observer = new JPanel();
            
//            设置每次插入图片的位置
            width = image.getWidth() * countw;
            countw = countw + 1 ;
            if (width > imageWight) {
                height = image.getHeight()+height;
                countw = 0;
            }   
//            图片插入
            graphics.drawImage(image, width, height, observer);
        }
        
//        写入指定位置
        ImageIO.write(bufferedImage, PICTURE_SUFFIX_NO_SPOT, new File(GROUP_PICTURE_FOLDER+filePath+PICTURE_SUFFIX_SPOT));
        return null;
    }
    
    

}
